#include "server.h"

Server::Server(QObject *parent) :
    QTcpServer(parent)
{
    m_root = m_userList.createElement("Package");
    m_userList.appendChild(m_root);
}
void Server::incomingConnection(int socketId)
{
    ///when a connect coming,new a thread to deal with the client
    ///alone
    ClientThread *client = new ClientThread(socketId,m_userList);
    client->start();

    ///connect with the widget,so the widget can add or delete the client's information to the table widget
    connect(client,SIGNAL(NewConnection(QString,QString,QString,int)),this,SLOT(processNewConnection(QString,QString,QString,int)));
    connect(client,SIGNAL(DisConnection(QString,QString,QString,int)),this,SIGNAL(DisConnection(QString,QString,QString,int)));
    connect(this,SIGNAL(serverClose()),client,SLOT(processServerClose()));
}
void Server::processNewConnection(QString uid, QString nickname, QString ip, int port)
{

    QDomElement user = m_userList.createElement("User");
    QDomElement nickNameE = m_userList.createElement("Name");
    QDomElement IPE = m_userList.createElement("IP");
    QDomElement PortE = m_userList.createElement("Port");

    QDomText nickNameT = m_userList.createTextNode(nickname);
    QDomText IPT = m_userList.createTextNode(ip);
    QDomText PortT = m_userList.createTextNode(QString().setNum(port));


    ///add a user to the DOM
    m_root.appendChild(user);
    user.appendChild(nickNameE);
    user.appendChild(IPE);
    user.appendChild(PortE);

    nickNameE.appendChild(nickNameT);
    IPE.appendChild(IPT);
    PortE.appendChild(PortT);

    emit NewConnection(uid,nickname,ip,port);

}

